package com.wind.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author： BeiYan
 * @Date： 2016-10-15 15:26
 * @Description:配置文件读取工具类
 */

public final class PropsUtil {

    private static final Logger logger = LoggerFactory.getLogger(PropsUtil.class);

    /**
     * 加载配置文件
     *
     * @param fileName 文件名
     * @return
     */
    public static Properties loadProps(String fileName) {
        Properties properties = null;
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            if (is == null) {
                throw new FileNotFoundException(fileName + " file is not found");
            }
            properties = new Properties();
            properties.load(is);
        } catch (IOException e) {
            logger.error("load prpperties file failure ", e);
        } finally {

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error("close the input stream failure", e);
                }
            }
        }
        return properties;

    }

    public static String getString(Properties properties, String key, String defaultValue) {
        String value = defaultValue;
        if (properties.containsKey(key)) {
            value = properties.getProperty(key);
        }
        return value;
    }


    public static String getString(Properties properties, String key) {
        String value = "";
        return getString(properties, key, value);
    }
    

    public static int getInt(Properties properties, String key) {
        int value = 0;
        return getInt(properties, key, value);
    }

    public static int getInt(Properties properties, String key, int defaultValue) {
        int value = defaultValue;
        if (properties.containsKey(key)) {
            value = CastUtil.castInt(properties.getProperty(key));
        }
        return value;
    }

    public static boolean getBoolean(Properties properties, String key) {
        boolean value = false;
        return getBoolean(properties, key, value);
    }

    public static boolean getBoolean(Properties properties, String key, boolean defaultValue) {
        boolean value = defaultValue;
        if (properties.containsKey(key)) {
            value = CastUtil.castBoolean(properties.getProperty(key));
        }
        return value;
    }


}

